
from flask import session,current_app,jsonify,request
# from info.modules.news import new_blue
from info.utils.commons import login_required
from . import news_blue
from flask import render_template,g
from info.models import User,News,Category,Comment
from info.utils.response_code import RET
from info import constants,db


@news_blue.route('/')
@login_required
def index():
    # data = 'i am king666'
    user=g.user
    # if user:
    # data={

            # 'user_info':user.to_dict
        #  'user_info':user.to_dict() if user else None
        # }
    # else:
    #     data={
    #         'user_info':None
    #     }
# #新闻分类展示
#     二、加载新闻分类
#     1、查询新闻分类数据，mysql
#     ca = Category.query.all()
#     2、判断查询结果是否有数据
#     3、如果有数据，遍历查询结果，调用模型类中的to_dict函数
#     4、返回新闻分类数据
    try:
        categorys=Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询加载新闻数据数据失败')
    if not categorys:
        return jsonify(errno=RET.NODATA,errmsg='没有查到加载新闻数据')
    category_list=[]
    for category in categorys:
        category_list.append(category)



# 点击排行
    try:
        news_rank=News.query.filter().order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻排行数据失败')
    if not news_rank:
        return jsonify(errno=RET.NODATA,errmsg='没有查询到新闻排行数据')
    news_rank_list=[]
    for news in news_rank:
        # news是一个对象所以需要调用to_dict转成字典
        news_rank_list.append(news.to_dict())

    data={
        'user_info':user.to_dict()if user else None,
        'news_rank_list':news_rank_list,
        'category_list':category_list
    }

    return render_template('news/index.html',data=data)

@news_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')



@news_blue.route('/news_list')
def get_news_list():
    # 获取参数
    cid=request.args.get('cid','1')
    page=request.args.get('page','1')
    per_page=request.args.get('per_page','10')
    try:
        cid,page,per_page=int(cid),int(page),int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='转化数据类型失败')
    # 查询cid对应的新闻
    filter=[News.status==0]
    if cid>1:
        filter.append(News.category_id==cid)
    try:
        paginate=News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻列表数据库失败')
    news_list=paginate.items
    total_page=paginate.pages
    current_page=paginate.page
    news_dict_list=[]
    for news in news_list:
        news_dict_list.append(news.to_dict())
    data={
        'news_dict_list':news_dict_list,
        'total_page':total_page,
        'current_page':current_page
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)



@news_blue.route('/<int:news_id>')
@login_required
def news_detail(news_id):
    # 点击排行
    user=g.user
    try:
        news_rank=News.query.filter().order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻排行数据失败')
    if not news_rank:
        return jsonify(errno=RET.NODATA,errmsg='没有查询到新闻排行数据')
    news_rank_list=[]
    for news in news_rank:
        # news是一个对象所以需要调用to_dict转成字典
        news_rank_list.append(news.to_dict())


    # 新闻详情数据加载
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻详情数据失败')
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='没有新闻详情数据')
    # 每点击一次数据就加一
    news.clicks+=1
    # 把点击量提交到数据库中
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='提交点击量数据库失败')



    # 新闻收藏(主页面)
    user=g.user
    is_collected=False
    if user and (news in user.collection_news):
        is_collected=True
        # print(user.collection_news)

    # 新闻评论

    # 查询数据库
    try:
        comments=Comment.query.filter_by(news_id=news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻数据库失败')
    # if comments:
    comment_list=[]
    for commment in comments:
        comment_list.append(commment.to_dict())


    data={
        'user_info':user.to_dict()if user else None,
        'news_rank_list':news_rank_list,
        'news_detail':news.to_dict(),
        'is_collected':is_collected,
        'comments':comment_list

    }
    return render_template('news/detail.html', data=data)
    pass

@news_blue.route('/news_collect',methods=['POST'])
@login_required
def news_collect():
    user = g.user
    # 前端是ajax,收藏是局部刷新，所以用request.json获取前端json数据
    news_id=request.json.get('news_id')
    action=request.json.get('action')
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
    try:
        news_id=int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数类型错误')
    if action not in (['collect', 'cancel_collect']):
        return jsonify(errno=RET.PARAMERR, errmsg='参数范围错误')

    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')
    # if not news_id:
    #     return jsonify(errno=RET.PARAMERR,errmsg='没有获取到新闻ID')

    # 查询数据库获取新闻
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据库失败')
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='没有获取到新闻')
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='提交收藏到数据库失败')
    return jsonify(errno=RET.OK,errmsg='收藏成功')


@news_blue.route('/news_comment',methods=['POST'])
@login_required
def news_commment():
    news_id=request.json.get('news_id')
    comments=request.json.get('comment')
    parent_id=request.json.get('parent_id')
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')
    if not all([news_id,comments]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据库失败')
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='没有新闻数据')
    # 初始化新闻类
    comment=Comment()
    comment.user_id=user.id
    comment.news_id=news_id
    comment.content=comments
    if parent_id:
        comment.parent_id=parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='提交评论到数据库失败')
    data={
        'comment':comment.to_dict()
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)
    pass


